package com.example.lark_auth;

import androidx.annotation.NonNull;
import android.content.Context;
import android.content.Intent;
import android.app.Application;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import java.util.ArrayList;
import com.ss.android.larksso.CallBackData;
import com.ss.android.larksso.IGetDataCallback;
import com.ss.android.larksso.LarkSSO;

import android.widget.Toast;

/** LarkAuthPlugin */
public class LarkAuthPlugin
    implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.NewIntentListener {
  /// The MethodChannel that will the communication between Flutter and native
  /// Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine
  /// and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private static final String TAG = "LarkAuthPlugin";
  private Activity currentActivity;

  @Override
  public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
    Log.i(TAG, "----onAttachedToActivity-----");
    currentActivity = binding.getActivity();
    binding.addActivityResultListener(new PluginRegistry.ActivityResultListener() {
      @Override
      public boolean onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
        Log.i(TAG, "----onActivityResult-----" + requestCode + "resultCode:" + resultCode + "indent:" + data);
        LarkSSO.inst().parseIntent(currentActivity, data);
        return false;
      }
    });
    binding.addOnNewIntentListener(this);
    currentActivity.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
      @Override
      public void onActivityCreated(Activity activity, Bundle bundle) {

      }

      @Override
      public void onActivityStarted(Activity activity) {

      }

      @Override
      public void onActivityResumed(Activity activity) {

        Log.i(TAG, "----onActivityResumed-----" + activity.getIntent().getExtras());
        LarkSSO.inst().parseIntent(currentActivity, activity.getIntent());
      }

      @Override
      public void onActivityPaused(Activity activity) {

      }

      @Override
      public void onActivityStopped(Activity activity) {

      }

      @Override
      public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

      }

      @Override
      public void onActivityDestroyed(Activity act) {

      }
    });
  }

  @Override
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
    // actBinding = binding;
    // currentActivity = binding.getActivity();
  }

  @Override
  public void onDetachedFromActivity() {
    // actBinding = null;
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {
    // actBinding = null;
  }

  @Override
  public boolean onNewIntent(Intent intent) {
    Log.i(TAG, "----onNewIntent-----" + intent.getExtras());
    LarkSSO.inst().parseIntent(currentActivity, intent);
    return true;
  }

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    Log.i(TAG, "----onAttachedToEngine-----111");
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "lark_auth");
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    Log.e(TAG, "log:" + call.method);
    switch (call.method) {
      case "startSSOVerify":
        String appId = call.argument("appId");
        String server = call.argument("server");
        String language = call.argument("language");
        ArrayList<String> scopeList = call.argument("scopeList");
        LarkSSO.Builder builder = new LarkSSO.Builder().setAppId(appId)
            .setServer(server)
            .setLanguage(language)
            .setScopeList(scopeList)
            .setContext(currentActivity);
        Log.e(TAG, appId);
        LarkSSO.inst().startSSOVerify(builder, new IGetDataCallback() {
          @Override
          public void onSuccess(CallBackData callBackData) {
            Log.e(TAG,
                "Auth Success, code is" + callBackData.code + ",codeVerifier is:" + callBackData.codeVerifier);
            result.success(callBackData.code);

          }

          @Override
          public void onError(CallBackData callBackData) {
            String errorMessage = "";
            switch (callBackData.code) {
              case "-1":
                errorMessage = "状态码校验失败，非当前SDK请求的响应";
                break;
              case "-2":
                errorMessage = "没有获得有效的授权码";
                break;
              case "-3":
                errorMessage = "用户取消授权";
                break;
              case "-4":
                errorMessage = "跳转飞书失败";
                break;
              case "-5":
                errorMessage = "授权失败";
                break;
              case "-6":
                errorMessage = "请求参数错误";
                break;
              default:
                errorMessage = "授权失败";
                break;
            }
            Toast.makeText(currentActivity,
                errorMessage,
                Toast.LENGTH_LONG).show();
            Log.e(TAG,
                "Auth Failed, errorCode is" + callBackData.code + ",codeVerifier is:" + callBackData.codeVerifier);
            result.error(callBackData.code, errorMessage, call.arguments);

          }
        });
        break;
      default:
        result.notImplemented();
        break;
    }

  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }
}
